import { View, Text, Image } from "@tarojs/components";
import { useEffect, useMemo, useRef, useState } from "react";
import ico_add_two from "@/assets/image/ico_add_two.svg";
import ico_jiantou_one from "@/assets/image/ico_jiantou_one.svg";

import "./index.scss";
import { useRouter } from "@tarojs/taro";
import { classifyDetail, classifyPost } from "@/services/entities/all";
import { uploadFileApi } from "@/helper/request/request";
import Taro from "@tarojs/taro";
import FormInput from "@/components/public/FormInput";
import AddAd from "./components/addAd";
import { back } from "@/helper/utils";
import { Status } from "@/constants/common";

const AddType = () => {
  const router = useRouter();
  const { params } = router;
  const { type, status, id, parentId = "" } = params;
  const disabled = status === Status.preview;
  const addTypeText = useMemo(() => {
    return type === "1" ? "大类" : "子类";
  }, [type]);
  const deleteIds = useRef<any>([]);

  const [form, setForm] = useState({
    icon: "",
    id: 0,
    name: "",
    parentId: 0,
    sort: 0,
  });

  const onChange = (key, value) => {
    if (disabled) {
      return;
    }
    const temp = { ...form };
    temp[key] = value;
    console.log(temp);
    setForm(temp);
  };

  const [list, setList] = useState<any[]>([]);
  const adList = useRef<any[]>([]);

  useEffect(() => {
    if (id) {
      classifyDetail({ id }).then((res: any) => {
        console.log("classifyDetail", res);
        setForm({
          icon: res.icon,
          id: res.id,
          name: res.name,
          parentId: res.parentId,
          sort: res.sort,
        });
        const adTmp = res.addClassifyStoreList?.map((item) => {
          return {
            id: item.id,
            banner: item.imageUrl ? item.imageUrl?.split(",") : [],
            name: item.name,
            orderBy: item.orderBy,
            storeId: item.storeId,
          };
        });
        adList.current = adTmp ?? [];
        setList(adTmp ?? []);
      });
    }
  }, [id]);

  const submit = () => {
    if (disabled) {
      return;
    }
    const bannerList = adList.current
      ?.filter((item) => {
        return item.banner && item.banner.length && item.name;
      })
      .map((item) => {
        const result: any = {
          id: item.id,
          imageUrl: item.banner?.join(","),
          storeId: item.storeId,
          name: item.name,
          orderBy: item.orderBy,
        };
        if (item.id) {
          result.id = item.id;
        }
        return result;
      });
    classifyPost({
      id: id,
      icon: form.icon,
      name: form.name,
      parentId: parentId,
      sort: form.sort,
      addClassifyStoreList: bannerList,
      deleteIds: deleteIds.current.join(","),
    }).then(() => {
      back();
    });
  };

  const chooseImage = () => {
    if (disabled) {
      return;
    }
    Taro.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        uploadFileApi(tempFilePaths[0]).then((data: any) => {
          onChange("icon", data.data);
        });
      },
    });
  };

  const clickAdd = () => {
    setList((old) => [...old, { banner: [], storeId: "", sort: old.length }]);
    adList.current.push({
      banner: [],
      name: "",
      storeId: "",
      orderBy: adList.current.length,
    });
  };

  return (
    <View className="add-type-container bg-page pb-80 border-box">
      <View className="flex-column">
        <Text className="mg-tb-24 ml-22 fs-24 lh-36 cl-A4A4A4">
          添加商家基本信息
        </Text>
        <FormInput
          disabled={disabled}
          value={form.name}
          label={`${addTypeText}名称`}
          placeholder={`请输入${addTypeText}名称`}
          onChange={(value) => {
            onChange("name", value);
          }}
        />
        <FormInput
          disabled={disabled}
          value={form.sort}
          type="number"
          label={`${addTypeText}排序`}
          placeholder={`请输入${addTypeText}排序`}
          onChange={(value) => {
            onChange("sort", value);
          }}
        />
        {type === "2" && (
          <View className="dis-flex align-center justify-between bg-ffffff pd-lr-22 pd-tb-28 border-box">
            <Text className="fs-28 lh-38 cl-848484">子类图标</Text>
            <View
              className="dis-flex align-center flex-1 justify-end "
              onClick={chooseImage}
            >
              <Image src={form.icon} className="img-36 ml-8" />
              <Image src={ico_jiantou_one} className="img-36" />
            </View>
          </View>
        )}
        {!disabled && (
          <View className="flex-center pd-tb-32 border-box">
            <View
              className="add-btn dis-flex align-center br-16 pd-tb-12 pd-lr-72 border-box"
              onClick={clickAdd}
            >
              <Image src={ico_add_two} className="img-36" />
              <Text className="ml-8 fs-28 lh-38 cl-007DDB">{`新增${addTypeText}广告`}</Text>
            </View>
          </View>
        )}
        {list?.map((item, index) => {
          const single = adList.current[index];
          console.log("single", single);
          return (
            <AddAd
              initValue={single}
              disabled={disabled}
              key={`${index}_${new Date().getTime()}`}
              addTypeText={addTypeText}
              onDelete={() => {
                const tmp = [...list];
                adList.current.splice(index, 1);
                const deleteItem = tmp.splice(index, 1);
                if (deleteItem[0].id) {
                  deleteIds.current.push(deleteItem[0].id);
                }
                console.log("111");
                setList(tmp);
              }}
              onChange={(value) => {
                adList.current[index] = value;
                console.log("adList.current", adList.current);
              }}
            />
          );
        })}
      </View>
      <View className="bottom pd-20  dis-flex align-center border-box">
        <View
          className="flex-1 flex-center pd-tb-20 border-box bg-007DDB br-8 fs-28 lh-38 cl-white"
          onClick={submit}
        >
          提交
        </View>
      </View>
    </View>
  );
};

export default AddType;
